<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MES智能客服</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .chat-header {
            background: #007bff;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 20px;
            border-bottom: 1px solid #eee;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
            max-width: 70%;
        }
        .user-message {
            background: #007bff;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        .ai-message {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        .chat-input {
            display: flex;
            padding: 20px;
            gap: 10px;
        }
        .chat-input input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .chat-input button {
            padding: 12px 24px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .chat-input button:hover {
            background: #0056b3;
        }
        .chat-input button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
        }
        .error {
            color: #dc3545;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h2>MES生产管理系统 - 智能客服</h2>
            <p>您好！我是您的AI助手，可以帮助您了解和使用MES系统功能</p>
        </div>
        
        <div class="chat-messages" id="chatMessages">
            <div class="message ai-message">
                <strong>AI助手：</strong>您好！我是MES生产管理系统的智能客服助手。我可以帮助您：<br>
                • 了解工单管理功能<br>
                • 解答工序流程相关问题<br>
                • 协助报工操作指导<br>
                • 解决系统使用问题<br><br>
                请问有什么可以帮助您的吗？
            </div>
        </div>
        
        <div class="chat-input">
            <input type="text" id="messageInput" placeholder="请输入您的问题..." maxlength="500">
            <button id="sendButton" onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        let currentSessionId = null;

        // 页面加载时创建新会话
        window.onload = async function() {
            await createNewSession();
        };

        // 创建新会话
        async function createNewSession() {
            try {
                const response = await fetch('/api/chat/session', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                if (result.success) {
                    currentSessionId = result.data;
                    console.log('新会话创建成功:', currentSessionId);
                }
            } catch (error) {
                console.error('创建会话失败:', error);
                showError('创建会话失败，请刷新页面重试');
            }
        }

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            const message = input.value.trim();

            if (!message) {
                return;
            }

            // 禁用输入
            input.disabled = true;
            sendButton.disabled = true;

            // 显示用户消息
            addMessage(message, 'user');
            input.value = '';

            // 显示加载状态
            const loadingDiv = addMessage('正在思考中...', 'ai', true);

            try {
                const response = await fetch('/api/chat/message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message
                    })
                });

                const result = await response.json();
                
                // 移除加载状态
                loadingDiv.remove();

                if (result.success && result.data) {
                    addMessage(result.data.reply, 'ai');
                    currentSessionId = result.data.sessionId;
                } else {
                    addMessage('抱歉，我暂时无法回答您的问题。', 'ai');
                    showError(result.msg || '服务器错误');
                }
            } catch (error) {
                loadingDiv.remove();
                console.error('发送消息失败:', error);
                addMessage('网络连接错误，请检查网络后重试。', 'ai');
                showError('网络连接失败');
            } finally {
                // 恢复输入
                input.disabled = false;
                sendButton.disabled = false;
                input.focus();
            }
        }

        // 添加消息到聊天窗口
        function addMessage(content, type, isLoading = false) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}-message`;
            
            if (isLoading) {
                messageDiv.className += ' loading';
            }

            const roleText = type === 'user' ? '您' : 'AI助手';
            messageDiv.innerHTML = `<strong>${roleText}：</strong>${content}`;
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
            
            return messageDiv;
        }

        // 显示错误信息
        function showError(message) {
            const messagesDiv = document.getElementById('chatMessages');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.textContent = `错误: ${message}`;
            messagesDiv.appendChild(errorDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>
